/**
 *---------------------------------------------------------------------------------------------------------------------
 *  @copyright Copyright (c) 2022  <dx_65535@163.com>.
 *
 *  @file       : main_unix_dgram.cc
 *  @author     : Xiang.D (dx_65535@163.com)
 *  @version    : 1.0
 *  @brief      : Blog: https://mp.weixin.qq.com/s/eoCPWMGbIcZyxvJ3dMjQXQ
 *  @date       : 2024/11/22
 *
 *
 *  Change History:
 *  <Date>     | <Version> | <Author>       | <Description>
 *---------------------------------------------------------------------------------------------------------------------
 *  2024/11/24 | 1.0.0.1   | Xiang.D        | Create file
 *---------------------------------------------------------------------------------------------------------------------
 *
 */
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "PSocket.h"
#include "EpollEventHandler.h"

using namespace std;

#define SPR_LOGD(fmt, args...) printf("MainUnDgram D: %4d " fmt, __LINE__, ##args)
#define SPR_LOGW(fmt, args...) printf("MainUnDgram W: %4d " fmt, __LINE__, ##args)
#define SPR_LOGE(fmt, args...) printf("MainUnDgram E: %4d " fmt, __LINE__, ##args)

int main(int argc, char *argv[])
{
    if (argc != 2 && argc != 3) {
        SPR_LOGE("As server usage: %s <curPath>\n", argv[0]);
        SPR_LOGE("As client usage: %s <curPath> <srvPath>\n", argv[0]);
        return -1;
    }

    string myPath = argv[1];
    string dstPath = (argc == 3) ? argv[2] : "";
    const auto& epollHandler = EpollEventHandler::GetInstance();
    auto pUnDgram = make_shared<PUnixDgram>([&](ssize_t ret, string bytes, string dstPath, void* arg) {
        if (ret <= 0) {
            SPR_LOGE("Read fail! (%s)\n", strerror(errno));
        }

        PUnixDgram* pUnDgram = reinterpret_cast<PUnixDgram*>(arg);
        if (!pUnDgram) {
            SPR_LOGE("pUnDgram is nullptr\n");
            return;
        }

        SPR_LOGD("# RECV FROM %s> %s \n", dstPath.c_str(), bytes.c_str());
        pUnDgram->Write("Read OK", dstPath);
        // sleep(1);
    });

    int ret = pUnDgram->AsUnixDgram(myPath);
    if (ret != -1) {
        SPR_LOGD("As UDP success!\n");
    }

    if (!dstPath.empty()) {
        pUnDgram->Write("Hello", dstPath);
    }

    epollHandler->EpollLoop();
    return 0;
}
